import React, { Component } from 'react';
import Taro from '@tarojs/taro';
import {SiteInfo, RecommendGood, Good, IndexDiyModuleGood} from 'src/utils/server.interface'
import Skeleton from 'taro-skeleton';
import {View, Image, Text, Navigator, Block} from '@tarojs/components'
import {AtIcon} from 'taro-ui'
import {http} from '../../utils/http'
import {STORE_INFO, STORE_PAGE, STORE_RECOMMEND_GOODS} from '../../constants/api'
import SwiperRecommend from '../../components/swiper-recommend/swiper-recommend'
import GoodShow from '../../components/good-show/good-show'
import {location} from '../../utils/location.service'
import {GetRequest, vcmonitor} from "../../utils/tools";
import {h5Wx} from "../../utils/h5.service";
import GzhAuth from "../../components/gzh-auth/gzh-auth"
import {lxH5Wx} from "../../utils/lx.h5.service";
import './store.scss'

interface StateType {
  storeInfo: SiteInfo
  recommendGoods: IndexDiyModuleGood[]
  pageGoods: Good[]
  loadMoreStatus: "more" | "loading" | "noMore"
  showLoading: boolean
}

export default class Store extends Component {
  state: StateType = {
    storeInfo: {
      address: '',
      logo: '',
      service_tel: '',
      uuid: '',
      name: ''
    },
    recommendGoods: [],
    pageGoods: [],
    loadMoreStatus: 'more',
    showLoading: true,
  }
  id = ''
  page = 1

  async UNSAFE_componentWillMount() {
    if (process.env.TARO_ENV === 'h5') {
      await h5Wx.getConfig()
    }
    Taro.showLoading({title: '加载中...'})
    this.id = Taro.getCurrentInstance().router.params.sid || ''
    const storeInfoData = await http.get<SiteInfo>(STORE_INFO, {uuid: this.id})
    let storeInfo = {}
    if (storeInfoData) {
      storeInfo = storeInfoData
    } else {
      const timer = setTimeout(() => {
        clearTimeout(timer)
        Taro.navigateBack()
      }, 1500)
    }
    const recommendGoodsData = await http.get<RecommendGood[]>(STORE_RECOMMEND_GOODS, {sid: this.id})
    const pageGoods = await this.getPageGoods(this.page)
    this.setState({pageGoods, showLoading: false, storeInfo, recommendGoods: recommendGoodsData})
    Taro.hideLoading()
  }

  async getPageGoods(page) {
    const pageGoodsData = await http.get<Good[]>(STORE_PAGE, {k: '', sid: this.id, p: page})
    if (pageGoodsData) {
      if (pageGoodsData.length < 10) {
        this.setState({loadMoreStatus: 'noMore'})
      } else {
        this.setState({loadMoreStatus: 'more'})
      }
      return pageGoodsData
    } else {
      return []
    }
  }

  makePhone() {
    Taro.makePhoneCall({
      phoneNumber: this.state.storeInfo.service_tel
    })
  }

  async navigate() {
    const {storeInfo} = this.state
    const address = storeInfo.address
    const latitude = +storeInfo.latitude
    const longitude = +storeInfo.longitude
    if (latitude && longitude) {
      lxH5Wx.navigation(latitude, longitude)
    } else {
      const ret = await location.getCoordinate(address)
      if (ret) {
        lxH5Wx.navigation(ret.lat, ret.lng, address)
      }
    }
  }

  async onReachBottom() {
    if (this.state.loadMoreStatus !== 'noMore') {
      this.setState({loadMoreStatus: 'loading'})
      this.page++
      const old = this.state.pageGoods
      const newData = await this.getPageGoods(this.page)
      this.setState({pageGoods: [...old, ...newData]})
    }
  }

  recommendMore() {
    let mpkey = ''
    const uInfo = Taro.getStorageSync('user') || ''
    if (uInfo && uInfo.mpkey && uInfo.mpkey !== 'undefined') {
      mpkey = uInfo.mpkey
    }
    Taro.navigateTo({url: '/main/recommend-list/recommend-list?sid=' + this.id + '&mpkey=' + mpkey})
  }

  async componentDidShow() {
    vcmonitor(this)
  }

  render() {
    const {storeInfo, pageGoods, recommendGoods, showLoading} = this.state
    return (
      <View className='store-root'>
        <GzhAuth />
        <View className='header'>
          <View className='head-box'
            style="background-Image: url('https://resource.ivcheng.com/resources/images/head_bg.jpg')"
          >
            <View className='head-box-wrap'>
              <Image className='head-img' src={storeInfo.logo} mode='widthFix' />
              <View className='head-text'>
                <Text className='title'>{storeInfo.name}</Text>
              </View>
            </View>
            <Navigator className='search-box' url='/common/search/search'>
              <AtIcon value='search' size='16' />
              <Text>搜索</Text>
            </Navigator>
          </View>
          <View className='head-info'>
            <View>
              <AtIcon value='map-pin' size='16' />
              <Text>{storeInfo.address}</Text>
            </View>
            <View className='btn-box'>
              <View className='btn' onClick={this.navigate.bind(this)}>
                <AtIcon prefixClass='xxhz' value='daohang' size='16' />
                <Text className='btn-text'>导航</Text>
              </View>
              <View className='tiao' />
              <View className='btn' onClick={this.makePhone.bind(this)}>
                <AtIcon prefixClass='xxhz' value='phone' size='16' />
                <Text className='btn-text'>电话</Text>
              </View>
            </View>
          </View>
        </View>
        {recommendGoods && recommendGoods.length > 0 && <View className='recommend'>
          <SwiperRecommend data={recommendGoods} title='商家推荐'
            clickMore={this.recommendMore.bind(this)}
          />
        </View>}
        {pageGoods && pageGoods.length > 0 && <View className='other'>
          <View className='title'>逛逛其它产品</View>
          <View className='content'>
            <Skeleton loading={showLoading} row={5} rowHeight={130}>
              <Block>
                {pageGoods.map((item, index) => <Navigator key={index} url={item.url} className='item'><GoodShow title={item.name}
                  image={item.img}
                  price={item.price}
                  markPrice={item.market_price}
                /></Navigator>)}
              </Block>
            </Skeleton>
          </View>
        </View>}
      </View>
    )
  }
}
